from mongoengine import QuerySet
from rest_framework.response import Response
from rest_framework import permissions, status
from rest_framework_mongoengine import viewsets

from authorshow.models.models import StandardResultSetPagination

from authorshow.models.utils import create_coll_id
from orgswords.models import OrgsWords
from orgswords.serializer import OrgsWordsSerializer


class OrgsWordsViewSet(viewsets.ModelViewSet):
    serializer_class = OrgsWordsSerializer
    queryset: QuerySet = OrgsWords.objects.all()

    # 用于分页
    pagination_class = StandardResultSetPagination
    # 权限控制
    permission_classes = (
        permissions.IsAuthenticatedOrReadOnly,
    )

    def create(self, request, *args, **kwargs):
        """
        创建一个新的instance,自动生成唯一的id值.
        """
        data = request.data
        data['id'] = str(create_coll_id(queryset=self.get_queryset()))
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(data=serializer.data, status=status.HTTP_201_CREATED, headers=headers)
